package com.jianbing.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.Result;
import com.jianbing.entity.WhiteIp;
import com.jianbing.exception.ServiceException;
import com.jianbing.util.IPUtil;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

/**
 * Created with IntelliJ IDEA. User: LFL Date: 2017/5/3 Time: 14:38 Description:
 */
@Controller
@RequestMapping(value = "/whiteIP")
public class WhiteIpController {
	Logger logger = Logger.getLogger(WhiteIpController.class);

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result add(HttpServletRequest request, HttpServletResponse response, @ModelAttribute WhiteIp ip) {
		Result result = new Result();
		try {
			BasicDBObject queryObject = new BasicDBObject();
			queryObject.append("ipAddress", ip.getIpAddress());
			WhiteIp existWhiteIp = MongoDBDao.findOne(TableUtil.whiteIp, WhiteIp.class, queryObject);
			if (existWhiteIp == null) {
				MongoDBDao.insert(TableUtil.whiteIp, ip);
				List<String> whiteList = IPUtil.getWhiteIPList();
				whiteList.add(ip.getIpAddress());
				IPUtil.setWhiteIPList(whiteList);
			}
		} catch (ServiceException e) {
			result.setCode(-1);
			result.setMsg("系统异常");
		}
		return result;
	}

	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public Result query(HttpServletRequest request, HttpServletResponse response) {
		Result result = new Result();
		ModelMap model = new ModelMap();
		List<WhiteIp> list = MongoDBDao.queryForList(TableUtil.whiteIp, WhiteIp.class, null, null, null, null, null);
		model.addAttribute("whiteIpList", list);
		result.setData(model);
		return result;
	}
}
